package com.xywy.broadcast;

import java.util.Calendar;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

import com.xywy.common.util.FileUtil;
import com.xywy.find.bean.Remind;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;

public class RemindService extends Service {

	private List<Remind> reminds; // 用來做發現裏面的提醒
//	private SharedPreferences sp;
//	private String userid;
	private User current_user;
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	@Override
	public int onStartCommand(Intent i, int flags, int startId) {
		Log.e("remid service---","onStartCommand");
		reminds = FileUtil.getList(current_user.getUserid() + "reminds");
		
		if (reminds != null && reminds.size() > 0) {
			for (Remind remind : reminds) {
				AlarmManager mAlManger = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
				long time = remind.getTime();
				Intent intent = new Intent(this, RemindBroadCast.class);
				intent.setAction(RemindBroadCast.REMINDACTION);
				PendingIntent pi = PendingIntent.getBroadcast(this, 0,
						intent,
						Intent.FLAG_ACTIVITY_NEW_TASK);
				if(remind.getType() == 2){
					intent.putExtra("message", "您该测体重啦");
				}else {
					intent.putExtra("message", "您该吃药啦");
				}
				Calendar c = Calendar.getInstance();
					c.setTimeInMillis(remind.getTime());
					int hour = c.get(Calendar.HOUR_OF_DAY);
					int minute = c.get(Calendar.MINUTE);
					c = Calendar.getInstance();
					c.set(Calendar.HOUR_OF_DAY, hour);
					c.set(Calendar.MINUTE, minute);
					time = c.getTimeInMillis();
					if(time < System.currentTimeMillis()){
						time += 1000*60*60*24;
					}
				mAlManger.setInexactRepeating(AlarmManager.RTC_WAKEUP, time,
						1000 * 60 * 60 * 24 , pi);
			}
		}
		return super.onStartCommand(i, flags, startId);
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
//		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		current_user = UserKeeper.getCurrentUser(this);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.e("---tag---", "onDestroy---");
		super.onDestroy();
	}

}
